const crypto = require("crypto-js");

class Auth {
  host;
  date;
  authorization;
  signature;
  APISecret;
  APIKey;
  constructor(APIKey, APISecret, host) {
    this.APIKey = APIKey;
    this.APISecret = APISecret;
    this.host = host;
  }

  tmpStr() {
    this.date = new Date().toUTCString();
    this.authorization = `host: ${this.host}\ndate: ${this.date}\nGET /v2.1/chat HTTP/1.1`;
  }

  hmacToBase64() {
    const signatureSha = crypto.HmacSHA256(this.authorization, this.APISecret);
    this.signature = crypto.enc.Base64.stringify(signatureSha);
  }

  getAuthSignUrl() {
    this.tmpStr();
    this.hmacToBase64();
    const signStr = `api_key="${this.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${this.signature}"`;
    const buff = Buffer.from(signStr);
    const base64data = buff.toString("base64");
    return `ws://${this.host}/v2.1/chat?authorization=${base64data}&date=${this.date}&host=${this.host}`;
  }
}

module.exports = Auth;
